import random
import re

import requests
from django.contrib import auth
from django.contrib.auth import login
from django.utils.decorators import method_decorator
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.ten_auth.models import User, OAuthWeixinUser, Channel, Article, Comment, Label
from utils.sendmobile2 import Sample
from utils.simmiddleware01 import login_required_my
from utils.ten_token import ten_token


# Create your views.py here.


# 发送短信验证码
class SendSMS(APIView):
    def get(self, request, mobile):
        if not re.match(r'^1[34578]\d{9}$', mobile):
            return Response({'msg': '手机号码格式错误'})

        number = str(random.randint(100000, 999999))
        Sample.main(number=number, mobile=mobile)
        redis_conn = get_redis_connection()
        redis_conn.setex('sms:%s' % mobile, 60 * 5, number)
        return Response({'success': True, 'sms_code': number, 'message': '发送成功'})


# 注册
class Register(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        username = request.data.get('username')
        password = request.data.get('password')
        sms_code = request.data.get('sms_code')

        if not all([mobile, password, sms_code, username]):
            return Response({'msg': '缺少必传参数'}, status=400)

        if not re.match(r'^1[34578]\d{9}$', mobile):
            return Response({'msg': '手机号码格式错误'}, status=400)
        obj = User.objects.filter(mobile=mobile)
        if obj:
            return Response({'msg': '手机号已注册'}, status=400)
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return Response({'msg': '密码格式错误'}, status=400)

        redis_conn = get_redis_connection()
        code = redis_conn.get('sms:%s' % mobile)
        if code is None:
            return Response({'msg': '验证码已过期'}, status=400)
        if code.decode() != sms_code:
            return Response({'msg': '验证码错误'}, status=400)
        try:
            user = User.objects.create_user(username=username,
                                            mobile=mobile,
                                            password=password,
                                            avatar='http://s7ph6efw7.hn-bkt.clouddn.com/asset-photo.png')
        except:
            return Response({'msg': '注册失败'}, status=400)
        login(request, obj)
        token = ten_token.generate_tokens(user.id)
        dict1 = {

            'token': token,
            'username': user.username,
            'avatar': user.avatar if user.avatar else '',
            'id': user.id

        }

        return Response(dict1)


# 登录
class Authorize(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        if not all([username, password]):
            return Response({'msg': '缺少必传参数'}, status=400)
        if not re.match(r'^1[34578]\d{9}$', username):
            return Response({'msg': '手机号码格式错误'}, status=400)
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return Response({'msg': '密码格式错误'}, status=400)
        try:
            User.USERNAME_FIELD = 'mobile'
            user = auth.authenticate(username=username, password=password)
        except:
            return Response({'msg': '密码错误'}, status=400)
        if user is None:
            return Response({'msg': '用户名或密码错误'}, status=400)
        token = ten_token.generate_tokens(user.id)
        login(request, user)
        dict1 = {
            'token': token,
            'username': user.username,
            'avatar': user.avatar if user.avatar else '',
            'id': user.id
        }

        a1 = Response(dict1)
        a1.set_cookie('user_id', user.id)

        return a1

    # 微博登录
    def get(self, request):
        code = request.GET.get('code')
        app_key = '3168812784'
        app_secret = '081f1e4de4aec823cde0251619345e14'
        token_url = "https://api.weibo.com/oauth2/access_token"
        params = {
            "client_id": app_key,
            "client_secret": app_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": "http://127.0.0.1:8080/weibo.html"
        }
        result = requests.post(url=token_url, data=params)

        data = result.json()
        uid = data.get("uid")
        access_token = data.get("access_token")
        get_user_url = "https://api.weibo.com/2/users/show.json"
        user_info = requests.get(url=get_user_url, params={"access_token": access_token, "uid": uid})
        data2 = user_info.json()
        openid = data2.get("id")
        obj = OAuthWeixinUser.objects.filter(openid=openid).first()
        if not obj:
            user = User.objects.create_user(username=data2.get("screen_name"),
                                            avatar='http://s7ph6efw7.hn-bkt.clouddn.com/asset-photo.png')
            OAuthWeixinUser.objects.create(openid=openid, user=user)
            login(request, user)
            token = ten_token.generate_tokens(user.id)
        else:
            user = obj.user
            login(request, obj.user)
            token = ten_token.generate_tokens(obj.user.id)

        dict1 = {
            'token': token,
            'username': user.username,
            'avatar': user.avatar if user.avatar else '',
            'id': user.id
        }

        return Response(dict1)


# 频道列表
class ChannelView(APIView):
    def get(self, request):
        channels = Channel.objects.all()
        list1 = [{'id': i.id, 'name': i.name} for i in channels]
        dict1 = {
            'results': list1,
            'count': len(channels),
            'previous': None,
            'next': None
        }
        return Response(dict1)


# 文章列表
class ChannelAllView(APIView):
    def get(self, request, id):
        if id == '-1':
            articles = Article.objects.all()
        else:
            obj = Channel.objects.filter(id=id).first()
            if not obj:
                return Response({'msg': '频道不存在'}, status=400)
            articles = obj.articles.all()
        list1 = []
        for i in articles:
            list1.append({
                'id': i.id,
                'title': i.title,
                'content': i.content,
                'createtime': i.createtime,
                'user': {
                    'id': i.user.id,
                    'username': i.user.username,
                    'avatar': i.user.avatar if i.user.avatar else '',
                    'article': [],
                    'fans': []
                },
                'collected_users': [i.id for i in i.collected_users.all()],
                'collected': False,
                'image': i.image

            })
        dict1 = {
            'count': len(articles),
            'previous': None,
            'next': None,
            'results': list1
        }
        return Response(dict1)

    # 点击收藏
    @method_decorator(login_required_my, name='put')
    def put(self, request, id):
        user_id = request.session.id
        obj = Article.objects.filter(id=id).first()
        if obj.collected_users.filter(id=user_id).first():
            obj.collected_users.remove(User.objects.get(id=user_id))
            obj.save()
            return Response({
                'message': '取消收藏成功',
                'success': True
            })
        obj.collected_users.add(User.objects.get(id=user_id))
        obj.save()

        return Response({
            'message': ' 收藏成功',
            'success': True
        })


# 文章详情
class ArticlelView(APIView):
    def get(self, request, id):
        obj = Article.objects.filter(id=id).first()
        if not obj:
            return Response({'msg': '文章不存在'}, status=400)
        user_article = []
        for i in obj.user.articles.all():
            user_article.append({
                'id': i.id,
                'title': i.title,
            })

        list1 = []
        for i in obj.comments.filter(parent=None).all():
            list1.append({
                'id': i.id,
                'user': {
                    'id': i.user.id,
                    'avatar': '',
                    'username': i.user.username,
                    'articles': [{'id': j.id, 'title': j.title} for j in i.user.articles.all()],
                    'fans': [j.id for j in i.user.idols.all()]
                },
                'subs': [{'id': j.id,
                          'content': j.content,
                          'article': [],
                          'user': {
                              'id': j.user.id,
                              'username': j.user.username,
                              'avatar': "",
                              'articles': [],
                              'fans': [k.id for k in j.user.idols.all()]
                          },
                          'subs': [],
                          'createtime': j.createtime
                          }
                         for j in i.subs.all()],
                'content': i.content,
                'createtime': i.createtime,
                'updatetime': i.updatetime,
                'parent': i.parent_id,
                'article': None
            })

        dict1 = {
            'id': obj.id,
            'user': {
                'id': obj.user.id,
                'username': obj.user.username,
                'avatar': obj.user.avatar if obj.user.avatar else '',
                'article': user_article,
                'fans': [i.id for i in obj.user.idols.all()]
            },
            'comments': list1,
            'subs': [],
            'title': obj.title,
            'content': obj.content,
            'image': obj.image,
            'createtime': obj.createtime,
            'updatetime': obj.updatetime,
            'visits': obj.visits,
            'thumbup': obj.thumbup,
            'comment_count': obj.comment_count,
            'labels': [i.id for i in obj.labels.all()],
            'collected_users': [i.id for i in obj.collected_users.all()],

            'channel': {
                'id': obj.channel.id,
                'name': obj.channel.name
            }

        }
        return Response(dict1)

    # 发布文章
    @method_decorator(login_required_my, name='put')
    def post(self, request):
        data = request.data
        content = data.get('content')
        labels = data.get('labels')
        title = data.get('title')
        channel = data.get('channel')
        image = data.get('image')

        obj = Article.objects.create(
            title=title,
            content=content,
            image=image,
            channel=Channel.objects.filter(id=channel).first(),
            user_id=request.session.id,
        )
        for i in labels:
            obj.labels.add(Label.objects.filter(id=i).first())
        obj.save()
        dict1 = {
            'articleid': obj.id,
            'message': '发布成功',
            'success': True
        }
        return Response(dict1)


# 评论文章
class CommentView(APIView):
    def post(self, request, id):
        data = request.data
        content = data.get('content')
        parent = data.get('parent')
        article = data.get('article')

        a1 = parent

        pobj = Comment.objects.filter(id=parent).first()
        if pobj:
            if pobj.parent:
                a1 = pobj.parent_id

        if parent:
            obj = Comment.objects.create(
                content=content,
                parent_id=a1,
                article_id=article,
                user_id=request.session.id
            )
        else:
            obj = Comment.objects.create(
                content=content,
                article_id=article,
                user_id=request.session.id
            )
        dict1 = {
            'message': '评论成功',
            'success': True
        }
        return Response(dict1)


# 搜索文章
class SearchView(APIView):
    def get(self, request):
        text = request.GET.get('text')
        articles = Article.objects.filter(title__icontains=text)
        list1 = []
        for i in articles:
            list1.append({
                'id': i.id,
                'title': i.title,
                'content': i.content,
                'createtime': i.createtime,
                'text': text
            })
        dict1 = {
            'count': len(articles),
            'next': None,
            'previous': None,
            'results': list1
        }
        return Response(dict1)
